using Godot;
using System;

public partial class Player : CharacterBody3D
{
	
	[Export]private float moveSpeed = 1f;
	[Export]private float dashSpeed = 2f;
	[Export] public float dashTime = 0.5f;
	
	[ExportGroup("Required Nodes")]
	[Export]public Sprite3D sprite;
	[Export]public AnimatedSprite3D animatedSprite;
	[Export]public StateMachine stateMachine;
	
	

	public PlayerStateGround groundState { get; private set; }
	public PlayerStateIdle idleState { get; private set; }
	public PlayerStateMove moveState { get; private set; }
	public PlayerStateDash dashState { get; private set; }

	public Vector2 direction { get; private set;}

	public override void _Ready()
	{
		groundState = new PlayerStateGround(this, stateMachine, animatedSprite);
		idleState = new PlayerStateIdle(this, stateMachine, animatedSprite);
		moveState = new PlayerStateMove(this, stateMachine, animatedSprite);
		dashState = new PlayerStateDash(this, stateMachine, animatedSprite);
		stateMachine.Start(idleState);
	}
	

	public override void _Input(InputEvent @event)
	{
		base._Input(@event);
		direction = Godot.Input.GetVector(
			GameConstants.INPUT_MOVE_LEFT, GameConstants.INPUT_MOVE_RIGHT, 
			GameConstants.INPUT_MOVE_FORWARD, GameConstants.INPUT_MOVE_BACKWARD
		);

		if (Input.IsActionJustPressed(GameConstants.INPUT_DASH))
		{
			stateMachine.SwitchState(dashState);
		}
		
	}
	

	public void AddMovement()
	{
		Velocity = new Vector3(direction.X, 0.0f, direction.Y) * moveSpeed;
		Flip();
		MoveAndSlide();
	}

	public void AddDash(float directionX)
	{
		Velocity = new Vector3(directionX, 0.0f, 0.0f) * dashSpeed;
		Flip();
		MoveAndSlide();
	}
	

	private void Flip()
	{
		if (Velocity.X == 0)
		{
			return;
		}
		
		bool osMovingLeft = Velocity.X < 0;
		animatedSprite.FlipH = osMovingLeft;
	}
}
